package com.tianyalei.wolf.mddesignlib.http;

import android.os.AsyncTask;

import com.tianyalei.wolf.mddesignlib.application.MyApplication;
import com.tianyalei.wolf.mddesignlib.base.BaseData;
import com.tianyalei.wolf.mddesignlib.utils.JsonUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by wolf on 2016/3/2.
 */
public class HttpTool {
    /**
     * 发送网络请求的方法
     */
    public static void sendRequest(int requestCode, HashMap<String, String> map,
                                   final GetDataCallBack call) {
        String url = getUrl(requestCode);
        send(isGet(requestCode), url, map, call);
    }

    /**
     * 真正的请求
     */
    private static void send(boolean get, String url, HashMap<String, String> map,
                             final GetDataCallBack call) {
        ResponseListener listener = new ResponseListener(call);
        // 如果是get请求
        if (get) {
            if (MyApplication.TOKEN_ID != null)
                OkHttpUtils.get().addHeader("token", MyApplication.TOKEN_ID).addHeader("system", "1").url(url).params(map).build().execute(listener);
            else
                OkHttpUtils.get().addHeader("system", "1").url(url).params(map).build().execute(listener);
            return;
        }

        //post请求
        if (map == null) {
            map = new HashMap<>();
        }
        if (map.size() == 0) {
            map.put("", "");
        }
        if (MyApplication.TOKEN_ID != null) {
            OkHttpUtils.post().addHeader("system", "1").addHeader("token", MyApplication.TOKEN_ID).url(url).params(map).build().execute(listener);
        } else {
            OkHttpUtils.post().addHeader("system", "1").url(url).params(map).build().execute(listener);
        }
    }

    /**
     * 根据请求码获取url地址
     */
    private static String getUrl(int requestCode) {
        String url = null;
        switch (requestCode) {
            case 100:
//                url = "http://192.168.36.220:8080/gmms_web/app/loginLoginAction.action";
                url = "http://192.168.36.220:8080/gps/app/loginAppUserAction.action";
                break;
            case 101:
//                url = "http://192.168.36.220:8080/gmms_web/app/aUrgentPersonAction.action";
                url = "http://192.168.36.220:8080/gps/app/registAppUserAction.action";
                break;
            default:
                break;
        }

        return url;
    }

    /**
     * 如果请求码是1XX则是get请求，如果是2XX则是post请求
     */
    private static boolean isGet(int requestCode) {
        if (requestCode >= 0 && requestCode < 100) {
            return true;
        }
        return false;
    }

    private static class ResponseListener extends Callback<Response> {
        private GetDataCallBack call;

        public ResponseListener(GetDataCallBack call) {
            this.call = call;
        }


        @Override
        public Response parseNetworkResponse(Response response) throws Exception {
            return response;
        }

        @Override
        public void onError(Call c, Exception e) {
            if (call != null)
                call.failure();
        }

        @Override
        public void onResponse(Response response) {
            MyApplication.TOKEN_ID = response.header("token");
            new BackgroundTask(call).execute(response);
        }

    }

    private static class BackgroundTask extends AsyncTask<Response, Void, String> {
        private GetDataCallBack mCallBack;

        public BackgroundTask(GetDataCallBack callBack) {
            mCallBack = callBack;
        }

        @Override
        protected String doInBackground(Response... response) {
            String content = "";
            try {
                content = response[0].body().string();
                //如果是session过期，或者未登录
                BaseData baseData = JsonUtil.toObject(content, BaseData.class);
                if (baseData.getCode() == -100) {
                    //跳转到登录页，进行自动登录操作
//                    LoginUtil.defaultLogin(MyApplication.getInstance(), new GetDataCallBack() {
//                        @Override
//                        public void failure() {
//                            super.failure();
//                            Intent i = new Intent(MyApplication.getInstance(), LoginActivity.class);
//                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            MyApplication.getInstance().startActivity(i);
//                        }
//                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                mCallBack.failure();
            }
            return content;
        }

        @Override
        protected void onPostExecute(String result) {
            mCallBack.success(result);
        }
    }
}
